#include "av.h"

extern
int lua_new_packet(lua_State * L) {
	AVPacket * pkt;
	int size = lua_gettop(L) >= 1 ? luaL_checkinteger(L, 1) : 0;
	pkt = av_mallocz(sizeof(AVPacket));
	if (!pkt) {
		luaL_error(L, "allocation error");
		return 0;
	}
	if (size > 0)
		av_new_packet(pkt, size);
	else
		av_init_packet(pkt);

	lua_push_packet(L, pkt);
	return 1;
}

static
void lua_packet_destroy(void * pkt) {
	av_free_packet(pkt);
	av_free(pkt);
}

DEFINE_TYPE_STRUCT(packet, AVPacket,
	LUA_OBJECT_PACKET_ID, lua_packet_destroy, 0)

DEFINE_INDEX_HEADER(packet, AVPacket)
	HANDLE_INDEX_ENTRY(pts, lua_pushinteger);
	HANDLE_INDEX_ENTRY(dts, lua_pushinteger);
	HANDLE_INDEX_ENTRY(pos, lua_pushinteger);
	HANDLE_INDEX_ENTRY(size, lua_pushinteger);
	HANDLE_INDEX_ENTRY(stream_index, lua_pushinteger);
	HANDLE_INDEX_ENTRY(duration, lua_pushinteger);
	if (strcmp(key, "data") == 0) {
		lua_pushlstring(L, (const char *) object->data, object->size);
		return 1;
	}
DEFINE_INDEX_TRAILER()

DEFINE_NEWINDEX_HEADER(packet, AVPacket)
DEFINE_NEWINDEX_TRAILER()

DEFINE_OBJECT_FUNCTIONS(packet, AVPacket)
